<template>
  <div class="qa-container">
    <div class="main-layout">
      <!-- 历史会话侧边栏 -->
      <div class="history-sidebar">
        <div class="sidebar-header">
          <h3>历史记录</h3>
          <el-button
            type="primary"
            size="small"
            @click="refreshHistory"
            :loading="isLoadingHistory"
          >
            新建对话
          </el-button>
          <el-button
            type="success"
            size="small"
            @click="generateReport"
            :loading="isGeneratingReport"
            :disabled="messages.length <= 1"
          >
            生成报告
          </el-button>
        </div>

        <div class="history-list">
          <div
            v-for="item in historyList"
            :key="item.id"
            class="history-item"
            :class="{ active: selectedHistoryId === item.id }"
            @click="loadHistory(item)"
          >
            <div class="history-title">
              {{ item.title }}
              <div class="history-actions">
                <el-icon class="edit-icon" @click.stop="showEditDialog(item)">
                  <Edit />
                </el-icon>
                <el-icon class="delete-icon" @click.stop="showDeleteConfirm(item)">
                  <Delete />
                </el-icon>
              </div>
            </div>
            <div class="history-date">{{ formatDate(item.createAt) }}</div>
          </div>
        </div>
      </div>

      <!-- 主聊天区域 -->
      <div class="chat-main">
        <el-card class="qa-card">
          <template #header>
            <div class="card-header">
              <span>智能问答助手</span>
            </div>
          </template>

          <div class="chat-area">
            <div
              v-for="(message, index) in messages"
              :key="index"
              :class="['message', message.role]"
            >
              <div class="avatar">
                <svg
                  v-if="message.role === 'user'"
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 24 24"
                  fill="#409eff"
                >
                  <path
                    d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"
                  />
                </svg>
                <svg
                  v-if="message.role === 'assistant'"
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 24 24"
                  fill="#67c23a"
                >
                  <path
                    d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-5 12H7v-2h7v2zm3-4H7V9h10v2z"
                  />
                </svg>
              </div>
              <div class="message-content">
                <template v-if="message.type === 'image'">
                  <img :src="message.content" class="message-image" />
                </template>
                <template v-else>
                  {{ message.content }}
                </template>
              </div>
            </div>
          </div>

          <div class="input-area">
            <el-input
              v-model="inputText"
              placeholder="请输入您的问题..."
              @keyup.enter="sendMessage"
              clearable
            >
            </el-input>
            <el-button type="primary" @click="sendMessage" :loading="isLoading"> 发送 </el-button>
            <el-button v-if="isLoading" type="danger" @click="stopChat" class="stop-button"
              >停止会话</el-button
            >
          </div>
        </el-card>
      </div>
    </div>

    <!-- 修改标题对话框 -->
    <el-dialog v-model="editDialogVisible" title="修改标题" width="30%">
      <el-input v-model="newTitle" placeholder="请输入新标题" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmEditTitle">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useSessionStorage } from '@vueuse/core'

const userId = useSessionStorage('qa_user_id', '')

// 初始化时生成用户ID
onMounted(() => {
  if (!userId.value) {
    userId.value = Date.now().toString(36) + Math.random().toString(36).substring(2)
  }
})
import {
  getHistoryPage,
  getHistoryConversationData,
  updateHistoryTitle,
  removeHistory,
  stopLLMChat,
} from '../api/fileApi'
import { fetchEventSource } from '@microsoft/fetch-event-source'
import { Edit, Delete } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { saveAs } from 'file-saver'
import { Document, Paragraph, Packer, TextRun } from 'docx'

// 消息相关
const messages = ref([
  { role: 'assistant', content: '您好！我是您的智能问答助手，请问有什么可以帮您？' },
])
const inputText = ref('')
const isLoading = ref(false)
const isGeneratingReport = ref(false)

// 历史记录相关
const historyList = ref([])
const selectedHistoryId = ref(null)
const editDialogVisible = ref(false)
const editingHistory = ref(null)
const newTitle = ref('')
const isLoadingHistory = ref(false)

const refreshHistory = async () => {
  selectedHistoryId.value = null
  messages.value = [
    { role: 'assistant', content: '您好！我是您的智能问答助手，请问有什么可以帮您？' },
  ]
  await fetchHistory()
}

const fetchHistory = async () => {
  isLoadingHistory.value = true
  try {
    const res = await getHistoryPage({ current: 1, size: 10, userId: userId.value })
    if (res.data.code === 200 && res.data.success) {
      historyList.value = res.data.data.records.map((item) => ({
        id: item.historyId,
        title: item.title,
        createAt: item.createAt,
      }))
    }
  } catch (error) {
    console.error('获取历史记录失败:', error)
  } finally {
    isLoadingHistory.value = false
  }
}

const loadHistory = async (history) => {
  selectedHistoryId.value = history.id
  try {
    const res = await getHistoryConversationData({
      userId: userId.value, // 需要从用户状态或登录信息中获取
      conversationId: history.id,
    })
    if (res.data.code === 200 && res.data.success) {
      messages.value = res.data.data
        .map((item) => [
          { role: 'user', content: item.question },
          { role: 'assistant', content: item.answer },
        ])
        .flat()
    }
  } catch (error) {
    console.error('加载历史会话失败:', error)
    messages.value = [{ role: 'assistant', content: `加载"${history.title}"的对话历史失败` }]
  }
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`
}

const showEditDialog = (history) => {
  editingHistory.value = history
  newTitle.value = history.title
  editDialogVisible.value = true
}

const showDeleteConfirm = (history) => {
  ElMessageBox.confirm('确定要删除这条历史记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      deleteHistory(history.id)
    })
    .catch(() => {})
}

const deleteHistory = async (id) => {
  try {
    const res = await removeHistory(id)
    if (res.data.code === 200 && res.data.success) {
      ElMessage.success('删除成功')
      refreshHistory()
    }
  } catch (error) {
    console.error('删除历史记录失败:', error)
    ElMessage.error('删除失败')
  }
}

const confirmEditTitle = async () => {
  if (!editingHistory.value || !newTitle.value.trim()) return

  try {
    const res = await updateHistoryTitle({
      historyId: editingHistory.value.id,
      title: newTitle.value,
    })

    if (res.data.code === 200 && res.data.success) {
      editingHistory.value.title = newTitle.value
      editDialogVisible.value = false
    }
  } catch (error) {
    console.error('修改标题失败:', error)
  }
}

const stopChat = () => {
  if (currentTaskId.value) {
    stopLLMChat(currentTaskId.value)
    isLoading.value = false
  }
}

const currentTaskId = ref(null)
const sendMessage = async () => {
  if (!inputText.value.trim()) return

  // 保存当前输入值
  const currentInput = inputText.value

  const userMessage = {
    role: 'user',
    content: currentInput,
  }
  messages.value.push(userMessage)
  let assistantMessageIndex =
    messages.value.push({
      role: 'assistant',
      content: '',
    }) - 1

  // 滚动到输入区域
  const scrollToBottom = () => {
    const chatArea = document.querySelector('.chat-area')
    if (chatArea) {
      chatArea.scrollTop = chatArea.scrollHeight
    }
  }

  nextTick(scrollToBottom)

  isLoading.value = true
  document.querySelector('.el-input__inner').disabled = true
  inputText.value = ''
  const ctrl = new AbortController()

  fetchEventSource('/api/llm/chat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      question: currentInput,
      userId: userId.value,
      historyId: selectedHistoryId.value,
    }),
    openWhenHidden: true,
    signal: ctrl.signal,
    onopen(e) {
      if (e.status !== 200) {
        // 接口异常代码
        throw err
      }
    },
    onmessage: (event) => {
      try {
        const jsonData = JSON.parse(event.data)
        selectedHistoryId.value = jsonData.historyId
        //停止会话消息
        currentTaskId.value = jsonData.taskId

        if (assistantMessageIndex === -1) {
          messages.value.push({
            role: 'assistant',
            content: jsonData.content,
          })
          assistantMessageIndex = messages.value.length - 1
        } else {
          messages.value[assistantMessageIndex].content += jsonData.content
        }
        scrollToBottom()
      } catch (e) {
        console.error('解析消息失败:', e)
      }
    },
    onerror: (err) => {
      ElMessage.error(err.message)
      isLoading.value = false
      document.querySelector('.el-input__inner').disabled = false
      document.querySelector('.el-button').disabled = false
      assistantMessageIndex = -1
      ctrl.abort()
      throw err // 直接抛出错误，避免反复调用
    },
    onclose: () => {
      inputText.value = ''
      isLoading.value = false
      document.querySelector('.el-input__inner').disabled = false
      document.querySelector('.el-button').disabled = false
      fetchHistory()
      assistantMessageIndex = -1
      ctrl.abort()
    },
  })
}

// 生成述职报告
const generateReport = async () => {
  isGeneratingReport.value = true
  try {
    // 创建Word文档
    const doc = new Document({
      sections: [
        {
          properties: {},
          children: [
            new Paragraph({
              children: [
                new TextRun({
                  text: '述职报告',
                  bold: true,
                  size: 28,
                }),
              ],
              alignment: 'center',
              spacing: { after: 200 },
            }),
            ...messages.value.reduce((acc, msg, index) => {
              if (msg.role === 'user') {
                acc.push(
                  new Paragraph({
                    children: [
                      new TextRun({
                        text: `问题${index + 1}: ${msg.type === 'image' ? '[图片]' : msg.content}`,
                        bold: true,
                      }),
                    ],
                    spacing: { after: 100 },
                  }),
                )
              } else if (
                msg.role === 'assistant' &&
                msg.content !== '您好！我是您的智能问答助手，请问有什么可以帮您？'
              ) {
                acc.push(
                  new Paragraph({
                    children: [
                      new TextRun({
                        text: `回答${index + 1}: ${msg.type === 'image' ? '[图片]' : msg.content}`,
                      }),
                    ],
                    spacing: { after: 100 },
                  }),
                )
              }
              return acc
            }, []),
          ],
        },
      ],
    })

    // 生成Blob并下载
    const blob = await Packer.toBlob(doc)
    saveAs(blob, `述职报告_${new Date().toLocaleDateString()}.docx`)

    ElMessage.success('报告生成成功')
  } catch (error) {
    console.error('生成报告失败:', error)
    ElMessage.error('生成报告失败')
  } finally {
    isGeneratingReport.value = false
  }
}

// 初始化时加载历史记录
fetchHistory()
</script>

<style scoped>
.qa-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  height: 85vh;
}

.main-layout {
  display: flex;
  flex: 1;
  gap: 20px;
  overflow: hidden;
}

.history-sidebar {
  width: 250px;
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.sidebar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
}

.history-list {
  flex: 1;
  overflow-y: auto;
}

.history-item {
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.history-item:hover {
  background-color: #f5f7fa;
}

.history-item.active {
  background-color: #ecf5ff;
  border-left: 3px solid #409eff;
}

.history-title {
  font-size: 14px;
  margin-bottom: 5px;
  color: #333;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.history-actions {
  display: flex;
  gap: 8px;
}

.history-date {
  font-size: 12px;
  color: #999;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.qa-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.chat-area {
  flex: 1 1 auto;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  height: 600px;
}

.message {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.message.user {
  flex-direction: row-reverse;
}

.message.assistant {
  flex-direction: row;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  flex-shrink: 0;
}

.message-content {
  display: inline-block;
  padding: 12px 16px;
  border-radius: 8px;
  max-width: 70%;
  white-space: pre-wrap;
  line-height: 1.6;
}

.message-content h1,
.message-content h2,
.message-content h3,
.message-content h4 {
  margin: 0.5em 0 0.25em;
  font-weight: bold;
}

.message-content p {
  margin: 0.5em 0;
}

.message-content ul,
.message-content ol {
  margin: 0.5em 0;
  padding-left: 1.5em;
}

.message-content li {
  margin: 0.25em 0;
}

.message-content code {
  background: rgba(0, 0, 0, 0.05);
  padding: 0.2em 0.4em;
  border-radius: 3px;
  font-family: monospace;
}

.message-content pre {
  background: rgba(0, 0, 0, 0.05);
  padding: 0.8em 1em;
  border-radius: 4px;
  overflow-x: auto;
  margin: 0.8em 0;
}

.message.user .message-content {
  background-color: #409eff;
  color: white;
}

.message.assistant .message-content {
  background-color: #f2f6fc;
  color: #333;
}

.message-image {
  max-width: 300px;
  max-height: 300px;
  border-radius: 4px;
  margin: 5px 0;
}

.input-area {
  display: flex;
  gap: 10px;
  padding: 20px 0 0;
  position: sticky;
  bottom: 0;
  background: white;
}

.edit-icon,
.delete-icon {
  color: #999;
  cursor: pointer;
  transition: color 0.2s;

  &:hover {
    color: #409eff;
  }
}

.delete-icon:hover {
  color: #f56c6c;
}
.stop-button {
  margin-left: 10px;
}
</style>
